<template>
	<view class="container">
		<!-- #ifdef H5 -->
		<view>
			<view>
				<view class="uni-form-item uni-column">
					<input class="uni-input" focus placeholder="请填写标题" />
				</view>
				<!-- <view class="uni-form-item uni-column">
					<view class="title">分类</view>
					<picker @change="politicalChange" :value="index" :range="politicals" v-model="political">
						<view class="picker">
							{{index>-1?politicals[index]:''}}
						</view>
					</picker>
				</view> -->
				<view class="toolbar">
					<view class="editfont icon-bold" @click="toolBarClick('bold')"></view>
					<view class="editfont icon-italic" @click="toolBarClick('italic')"></view>
					<view class="editfont icon-xiahuaxian1" @click="toolBarClick('header')"></view>
					<view class="editfont icon-underline" @click="toolBarClick('underline')"></view>
					<view class="editfont icon-strike" @click="toolBarClick('strike')"></view>
					<view class="editfont icon-alignleft" @click="toolBarClick('alignleft')"></view>
					<view class="editfont icon-aligncenter" @click="toolBarClick('aligncenter')"></view>
					<view class="editfont icon-alignright" @click="toolBarClick('alignright')"></view>
					<view class="editfont icon-link" @click="toolBarClick('link')"></view>
					<view class="editfont icon-image" @click="toolBarClick('imgage')"></view>
					<view class="editfont icon-qingkong" @click="toolBarClick('clear')"></view>
				</view>
				<view class="my_textarea" contentEditable="true" v-model="myTextarea">
					
				</view>
				<view class="pt10"><button class="primary booking-btn" @click="toolBarClick('submit')">提问</button></view>
				<qfAlert @closeAlert='closeAlert()' contentType='input' :isOpen='isOpen' ref='qfAlert_ipt' @submitAlert='submitLink'></qfAlert>
				<qfAlert @closeAlert='closeImageAlert()' contentType='image' :isOpen='isOpen4' ref='qfAlert' @submitAlert='submitImageLink'></qfAlert>
				<qfAlert contentType='text' content='请先选中要添加链接的文本!' :isOpen='isOpen2' @submitAlert='closeTip()'></qfAlert>
				<qfAlert @closeAlert='closeClean()' contentType='text' content='确定清空吗？' :isOpen='isOpen3' @submitAlert='isClean()'></qfAlert>
			</view>
		</view>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		
		<sl-filter :ref="'slFilter'" :topFixed="true" :isTransNav="true" :navHeight="0" :color="titleColor" :themeColor="themeColor" :menuList="menuList"
		 @result="result"></sl-filter>
		<view class="uni-form-item uni-column">
			<input class="uni-input" focus placeholder="请填写标题" v-model="title"/>
		</view>
		<view class="uni-form-item uni-column">
			<input class="uni-input" focus placeholder="请填写介绍" v-model="desc"/>
		</view>
		
		<view class="uni-form-item uni-column">
			<view class="grace-idcard-preview" v-if="thumb">
				<image :src="cdn_thumb "  @tap="selectImg" mode="aspectFill"></image>
			</view>
			<view @click="selectImg" class="cover">添加封面</view>
		</view>
		<view class="toolbar">
			<view class="editfont"><i class="iconfont icon-clearup" @tap="clear"></i></view>
			<view class="editfont"><i class="iconfont icon-charutupian" @tap="insertImage"></i></view>
			<view class="editfont"><i :class="'iconfont icon-zitijiacu '+(formats.bold ? 'ql-active' : '')" @tap="format('bold')"></i></view>
			<view class="editfont"><i :class="'iconfont icon-zitixieti '+(formats.italic ? 'ql-active' : '')" @tap="format('italic')"></i></view>
			<view class="editfont"><i :class="'iconfont icon-zitixiahuaxian '+(formats.underline ? 'ql-active' : '')" @tap="format('underline')"></i></view>
			<view class="editfont"><i class="iconfont icon--checklist" @tap="format('list', 'check')"></i></view>
			<view class="editfont"><i :class="'iconfont icon-youxupailie '+(formats.list === 'ordered' ? 'ql-active' : '')" @tap="format('list', 'ordered')"></i></view>
			<view class="editfont"><i :class="'iconfont icon-wuxupailie '+(formats.list === 'bullet' ? 'ql-active' : '')" @tap="format('list', 'bullet')"></i></view>
		</view>
		<editor id="editor" class="my_textarea" :placeholder="placeholder" @ready="onEditorReady" @input="editorChange"></editor>
		<view class="pt10"><button @click="submit" class="primary booking-btn">提问</button></view>
		<!-- #endif -->
	</view>
</template>

<script>
	import uParse from '../../components/uParse/src/wxParse.vue'
	import qfAlert from '../../components/qf-alert.vue'
	export default {
		name: "qf-editor",
		components: {
			uParse,
			qfAlert
		},
		data: function () {
			return {
				themeColor: '#000000',
				titleColor: '#666666',
				menuList: [{
						'title': '全部',
						'isSort': true,
						'key': 'subject',
						'detailList': []
					}
				],
				groupId: null,
				title: '',
				desc: '',
				thumb: '',
				cdn_thumb: '',
				category_id: '',
				content: '',
				myTextarea:'',
				link:'',
				imageLink:'',
				isOpen:false,
				isOpen2:false,
				isOpen3:false,
				isOpen4:false,
				endOffset:0,
				startOffset:0,
				endContainer:'',
				startContainer:'',
				placeholder: '请描述问题的具体情况',
				//politicals: ['java','python','大数据','人工智能', 'web前端'],
				//political: '',
				//index: 0,
			}
		},
		props: {
			
		},
		onLoad(options) {
			this.groupId = options.id;
			const platform = wx.getSystemInfoSync().platform
			this.isIOS = platform === 'ios';
			this.getMenus();
		},
		methods: {
			/* politicalChange(e){
				this.index = e.detail.value;
				this.political = this.politicals[this.index];
			}, */
			async getMenus(){
				await this.$http.post('api/common/category').then(res=>{
					if(res.code === this.sucCode){
						let list = res.data || [];
						if(list.length > 0){
							list = list.map((item)=>{
								let obj = {};
								obj.title = item.title;
								obj.value = item.id;
								return obj;
							});
							this.menuList[0].detailList = list;
						}
						
						
					}else{
						this.$mHelper.toast(res.msg);
					}
					
				}).catch(err=>{
					console.log(err);
				});
			},
			result(e){
				console.log('筛选结果',e);
				let filter = e;
				if(e.key === 'subject'){
					this.category_id = e.subject;
					
				}
				
			},
			submit(){
				
				if(!this.category_id){
					 uni.showToast({
					    icon: 'none',
						position: 'bottom',
					    title: '请选择分类',
					});
					return ;
				}
				if(!this.title){
					 uni.showToast({
					    icon: 'none',
						position: 'bottom',
					    title: '请输入标题',
					});
					return ;
				}
				if(!this.thumb){
					 uni.showToast({
					    icon: 'none',
						position: 'bottom',
					    title: '请添加封面',
					});
					return ;
				}
				if(!this.desc){
					 uni.showToast({
					    icon: 'none',
						position: 'bottom',
					    title: '请输入介绍',
					});
					return ;
				}
				if(!this.content){
					 uni.showToast({
					    icon: 'none',
						position: 'bottom',
					    title: '请输入内容',
					});
					return ;
				}
				
				//api/article/add
				this.$http.post('api/article/add',{
					category_id: this.category_id,
					title: this.title,
					content: this.content,
					thumb: this.thumb,
					desc: this.desc
				}).then(res=>{
					if(res.code === this.sucCode){
						uni.showModal({
							title: "提示",
							content: "保存成功,等待管理员审核",
							showCancel: false,
							confirmText: "确定",
							success: function (res) {
								uni.navigateBack();
							}
						});
					}else{
						this.$mHelper.toast(res.msg);
					}
				}).catch(err=>{
					console.log(err);
				})
				
				
				/* this.$api.memberPost('/group/show/add',{
					groupId: this.groupId,
					title: this.title,
					content: this.content,
				},{'Content-Type': 'application/x-www-form-urlencoded'}).then(r=>{
					if(r.data.code == 200){
						uni.showModal({
							title: "提示",
							content: "保存成功,等待管理员审核",
							showCancel: false,
							confirmText: "确定",
							success: function (res) {
								uni.navigateBack();
							}
						})
					}else{
						 uni.showToast({
						    icon: 'none',
							position: 'bottom',
						    title: '保存失败',
						});
					}
				}); */
			},
			editorChange: function(e){
				this.content = e.detail.html
			},
			onEditorReady(){
				uni.createSelectorQuery().select('#editor').context((res) => {
                    this.editorCtx = res.context
                }).exec()
			},
			format(name, value) {//格式
				if (!name) return
				// console.log('format', name, value)
				this.editorCtx.format(name, value)
			},
			undo() {//撤销
                this.editorCtx.undo()
            },
			clear() {
				this.editorCtx.clear({
					success: function (res) {
						console.log("clear success")
					}
				})
			},
			insertImage() {//插入图片
				const that = this
				wx.chooseImage({
					count: 1,
					success: (res) => {
						this.$api.upload(res.tempFilePaths[0]).then(r=>{
							let result = JSON.parse(r.data);
							let imgPath = result.body.uploadPath;
							that.editorCtx.insertImage({
								src: imgPath,
								data: {
								},
								width: '80%',
								success: function () {
									console.log('insert image success')
								}
							})
						});
					}
				})
			},
			toolBarClick(type) {
				if (type == 'bold') {
					var bold = document.execCommand("bold", false, null)
				} else if (type == "italic") {
					document.execCommand("italic", false, null)
				} else if (type == "header") {
					uni.showActionSheet({
						itemList: ["标题1", "标题2", "标题3", "标题4", "标题5", "标题6"],
						success: res => {
							switch (res.tapIndex) {
								case 0:
									document.execCommand("fontsize", false, 1);
									return;
								case 1:
									document.execCommand("fontsize", false, 2);
									return;
								case 2:
									document.execCommand("fontsize", false, 3);
									return;
								case 3:
									document.execCommand("fontsize", false, 4);
									return;
								case 4:
									document.execCommand("fontsize", false, 5);
									return;
								case 5:
									document.execCommand("fontsize", false, 6);
									return;
							}
						}
					})
				} else if (type == "underline") {
					alert("ok");
					document.execCommand("underline", false, null);
				} else if (type == "strike") {
					document.execCommand("strikeThrough", false, null)
				} else if (type == "alignleft") {
					document.execCommand("justifyLeft", false, null)
				} else if (type == "aligncenter") {
					document.execCommand("justifyCenter", false, null)
				} else if (type == "alignright") {
					document.execCommand("justifyRight", false, null)
				} else if (type == "link") {
					let selection  =  document.getSelection();
					console.log(selection.getRangeAt(0));
					if(selection.type == "Range"){
						var range = selection.getRangeAt(0);
						this.endOffset = range.endOffset;
						this.startOffset = range.startOffset;
						this.endContainer = range.endContainer;
						this.startContainer = range.startContainer;
						this.isOpen = 'true';
					} else {
						this.isOpen2 = 'true';
					}
				} else if (type == "imgage") {
					//document.execCommand("insertimage", false, "http://dinxin.suchenqiang.cn/public/upload/image/20190402/59310adb40594ae1fbdb5dd1fd009a15.jpg")
					let selection  =  document.getSelection();
					console.log(selection)
					if(selection.type != "None"){
						this.isOpen4 = 'true';
					}
				} else if (type == "clear") {
					/* uni.showModal({
						title: "提示",
						content: "确定清空?",
						success: res => {
							if (res.confirm) {
								this.myTextarea.target.innerHTML = "";
							}
						}
					}) */
					this.isOpen3 = 'true';
				} else if (type == "submit") {
					if(this.myTextarea!=''){
						alert(this.myTextarea.target.innerHTML);
						console.log(this.myTextarea.target.innerHTML);
					}
				} 
			},
			closeAlert() {
				this.isOpen = false;
			},
			closeImageAlert() {
				this.isOpen4 = false;
				this.$refs.qfAlert.imageLink = '';
			},
			closeTip() {
				this.isOpen2 = false;
			},
			closeClean() {
				this.isOpen3 = false;
			},
			submitLink(data) {
				this.link = this.$refs.qfAlert_ipt.link;
				this.isOpen = false;
				let selection  =  window.getSelection();
				let range  =  document.createRange();
				selection.removeAllRanges();
				range.setStart(this.startContainer,  this.startOffset);
				range.setEnd(this.endContainer,  this.endOffset);
				selection.addRange(range);
				document.execCommand("createlink", false, this.link);
			},
			submitImageLink(data) {
				this.isOpen4 = false;
				this.imageLink = this.$refs.qfAlert.imageLink;
				document.execCommand('insertHTML', false, "<image style='width:80%' src='"+this.imageLink+"'></image>");
				this.$refs.qfAlert.imageLink = '';
			},
			isClean() {
				this.closeClean();
				if(this.myTextarea!=''){
					this.myTextarea.target.innerHTML = "";
				}
			},
			
			/**
			 * 上传图片
			 */
			selectImg(type){
				let that = this;
				this.$mHelper.uploadImg((res)=>{
					uni.showLoading({ title: '正在上传中..' });
					that.$http
						.upload('api/common/upload', {
							filePath: res,
							name: 'file',
							// file: res, // 要上传文件资源的路径。
							
						})
						.then(res => {
							uni.hideLoading();
							let result = res.data;
							if (res.code == that.sucCode) {
								if(result.url){
									that.cdn_thumb = result.cdnurl;
									that.thumb = result.url;
								}
								
							} else {
								that.$mHelper.toast(res.msg);
							}
						})
						.catch(err => {
							that.$mHelper.toast('上传错误，请检查');
							uni.hideLoading();
						});
					
				});
				
			},
		}
	}
</script>

<style>
	@import '../../common/markdown.css';
	@import '../../common/iconfont.css';
	@import url("../../components/uParse/src/wxParse.css");
	
	.toolbar {
		width: 100%;
		border: none;
		box-shadow: 0 0upx 4upx rgba(0, 0, 0, 0.157), 0 0upx 4upx rgba(0, 0, 0, 0.227);
	}

	.toolbar .editfont {
		display: inline-block;
		cursor: pointer;
		height: 61.6upx;
		width: 61.6upx;
		margin: 0 0 0 0upx;
		font-size: 33upx;
		padding: 10upx 13upx 11upx 8upx;
		color: #757575;
		border-radius: 11upx;
		text-align: center;
		background: none;
		border: none;
		outline: none;
		line-height: 2.2;
		vertical-align: middle;
	}
	.my_textarea{
		width: 100%;
		min-height: 200px;
		box-sizing: border-box;
		outline: none;
		padding:28upx;
	}
	.my_textarea .img{
		width: 80%!important;
	}
	.toolbar .editor_submit{
		font-size: 12px;
		line-height: 35px;
	}
.ql-active {
  color: #22C704;
}
.iconfont {
  display: inline-block;
  width: 30px;
  height: 30px;
  cursor: pointer;
  font-size: 20px;
}
.cover{
	padding: 0 20rpx ;
	border: 1px solid #999999;
	border-radius: 10rpx;
	margin-left: 20rpx;
	margin-bottom: 40rpx;
	text-align: center;
	width: 160rpx;
}
.grace-idcard-preview{
	margin-left: 20rpx;
}
.grace-idcard-preview image{
	width: 200rpx;
	height: 200rpx;
}

</style>
